﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Awesomium.Core;
using MusicExplorer.ViewModel;
using MusicExplorer.WebRepository;

namespace MusicExplorer.View
{
    /// <summary>
    /// Logique d'interaction pour Player.xaml
    /// </summary>
    public partial class Player : UserControl
    {
        public Player()
        {
            InitializeComponent();
        }

        private void GoToPosition(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var slider = (Slider)sender;
            double position = e.GetPosition(slider).X;
            var ticks = Convert.ToInt64(position * slider.Maximum / slider.ActualWidth);
            
            if (((PlayerViewModel)DataContext).PlayingType == Internals.PlayingType.WebControl)
            {
                ((PlayerViewModel)DataContext).SetMp3YoutubePosition(ticks);
                webControl.ExecuteJavascript("seekTo(" + ticks + ")");
            }
            else ((PlayerViewModel)DataContext).SetMp3Position(ticks);
        }

        private void WebControlReady(object sender, Awesomium.Core.UrlEventArgs e)
        {
            JSObject jsobject = webControl.CreateGlobalJavascriptObject("jsobject");

            jsobject.Bind("EnableLoading", false, EnableLoading);
            jsobject.Bind("DisableLoading", false, DisableLoading);
            jsobject.Bind("GoToPosition", false, GoToPosition);
        }

        private void EnableLoading(object sender, JavascriptMethodEventArgs args)
        {
            (DataContext as PlayerViewModel).EnableYoutubeLoading();
        }

        private void DisableLoading(object sender, JavascriptMethodEventArgs args)
        {
            (DataContext as PlayerViewModel).DisableYoutubeLoading((bool)args.Arguments[0]);
        }

        private void GoToPosition(object sender, JavascriptMethodEventArgs args)
        {
            (DataContext as PlayerViewModel).SetMp3YoutubePosition((long)args.Arguments[0]);
        }
    }
}
